<?php

namespace app\company\controller;

use app\common\controller\CompanyController;
use app\common\service\annotation\ControllerAnnotation;
use app\common\service\annotation\NodeAnnotation;
use app\company\model\CompanyAuth;
use app\Request;
use think\App;
use think\response\Json;

/**
 * @ControllerAnnotation(title="角色管理")
 */
class Auth extends CompanyController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model     = new CompanyAuth();
        $this->joinTable = 'authMenu';
        $this->each      = true;
        $this->sort      = ['sort' => 'desc', 'id' => 'desc'];
    }

    public function each($list)
    {
        return $list->each(function ($vo)
        {
            $vo->menu_id = implode(',', $vo->authMenu()->column('company_menu_id'));
            return $vo;
        });
    }

    /**
     * @NodeAnnotation (title="新增")
     */
    public function add(Request $request): Json
    {
        $this->checkPost();
        $post               = $request->post();
        $menuIds            = !empty($post['menu_id']) ? $post['menu_id'] : '';
        $post['company_id'] = $this->companyId;
        $rule               = [
                'title|权限名称' => 'require|unique:company_auth,title,company_id^delete_time',
        ];
        $this->validate($post, $rule);
        try {
            $this->model->transaction(function () use ($post, $menuIds, &$save)
            {
                $save = $this->model->save($post);
                if ($save && $menuIds) {
                    $menuIds  = explode(',', $menuIds);
                    $authMenu = array_map(function ($menuId)
                    {
                        return ['company_auth_id' => $this->model->id, 'company_menu_id' => $menuId];
                    }, $menuIds);
                    $this->model->authMenu()->saveAll($authMenu);
                }
            });
        } catch (\Exception $e) {
            return $this->error('新增失败:' . $e->getMessage());
        }
        return $this->success('新增成功');
    }

    /**
     * @NodeAnnotation (title="编辑")
     */
    public function edit(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $rule = [
                'id' => 'require|integer'
        ];
        $this->validate($post, $rule);
        $row = $this->model->find($post['id']);
        if (!$row) return $this->error('数据不存在！');
        $menuIds = !empty($post['menu_id']) ? $post['menu_id'] : '';
        $this->sceneValidate($post, 'edit');
        try {
            $this->model->transaction(function () use ($post, $menuIds, $row, &$save)
            {
                $save = $row->save($post);
                if ($save && $menuIds) {
                    $menuIds = explode(',', $menuIds);
                    $this->model->authMenu()->where('company_auth_id', $row->id)->delete(true);
                    $authMenu = array_map(function ($menuId) use ($row)
                    {
                        return ['company_auth_id' => $row->id, 'company_menu_id' => $menuId];
                    }, $menuIds);
                    $this->model->authMenu()->saveAll($authMenu);
                }
            });
        } catch (\Exception $e) {
            return $this->error('编辑失败');
        }
        return $this->success('编辑成功');
    }

    /**
     * @NodeAnnotation (title="删除")
     */
    public function del(Request $request): Json
    {
        $this->checkPost();
        $post = $request->post();
        $this->validate($post,['id' => 'require']);
        $ids = explode(',', $post['id']);
        $row = $this->model->whereIn('id', $ids)->select();
        empty($row) && $this->error('数据不存在');
        try {
            foreach ($ids as $id) {
                $row = $this->model->with(['authMenu', 'userAuth'])->find($id);
                if ($row) $row->together(['authMenu', 'userAuth'])->delete(true);
            }
        } catch (\Exception $e) {
            return $this->error('删除失败:' . $e->getMessage());
        }
        return $this->success('删除成功');
    }
}